package com.hj.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.hj.system.entity.base.MenuEntity;
import com.hj.system.mapper.MenuMapper;
import com.hj.system.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wxf
 * @since 2021-04-02
 */
@Service
@Slf4j
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuEntity> implements MenuService {
    @Override
    public boolean save(MenuEntity menu) {
        log.info("增加菜单");
        menu.setCreateDate(new Date());
        Integer parentId = menu.getParentId();
        String p_queryCode = "0";
        if (parentId != 0) {
            MenuEntity parent = this.getById(parentId);
            p_queryCode = parent.getQueryCode();
        }
        //查询所有子节点
        List<MenuEntity> children = this.list(new QueryWrapper<MenuEntity>() {
        }.eq("parent_id", parentId));
        if (children.size() == 0) {
            menu.setQueryCode(p_queryCode + "-1");
        } else {
            Collections.sort(children, Comparator.comparingInt(o -> -Integer.valueOf(o.getMenuId())));
            MenuEntity lastChild = children.get(0);
            String c_queryCode = lastChild.getQueryCode();
            int length = c_queryCode.length();
            String prx = c_queryCode.substring(0, length - 1);
            String sub = c_queryCode.substring(length - 1, length);
            String n_queryCode = prx + (Integer.valueOf(sub) + 1);
            menu.setQueryCode(n_queryCode);
        }
        return SqlHelper.retBool(getBaseMapper().insert(menu));
    }

    @Override
    public boolean removeById(Serializable id) {
        MenuEntity menuEntity = this.getById(id);
        String queryCode = menuEntity.getQueryCode();
        return SqlHelper.retBool(getBaseMapper().delete(new QueryWrapper<MenuEntity>() {
        }.likeRight("query_code", queryCode)));
    }
}
